﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Web.Security;

namespace WebApplication.Models
{
    public class CheckSignature
    {
        //网站没有传入Token（或传入为NULL）情况下的默认Token
        public const string Token = "zhengshuai";



        /// <summary>
        /// 用来检查签名是否正确
        /// </summary>
        /// <param name="signature"></param>
        /// <param name="timespan"></param>
        /// <param name="noce"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static bool Check(string signature, string timespan, string noce, string token)
        {
            return signature == GetSignature(timespan, noce, token);
        }


        /// <summary>
        /// 根据参数timespan,noce,token
        /// </summary>
        /// <param name="timespan"></param>
        /// <param name="nonce"></param>
        /// <param name="token"></param> 
        /// <returns></returns>
        public static string GetSignature(string timespan, string nonce, string token = Token)
        {
            //token = token ?? Token;
            string[] arr = new[] {token,timespan,nonce }.OrderBy(z=>z).ToArray();
            string arrstring = string.Join("", arr);
            System.Security.Cryptography.SHA1 sha1 = System.Security.Cryptography.SHA1.Create();
            byte[] sha1Arr = sha1.ComputeHash(Encoding.UTF8.GetBytes(arrstring));
            StringBuilder enText = new StringBuilder();
            foreach (var b in sha1Arr)
            {
                enText.AppendFormat("{0:x2}", b);
            }
            return enText.ToString();
        }


        /// <summary>
        /// 根据参数得到
        /// </summary>
        /// <param name="timespan"></param>
        /// <param name="nonce"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static string GetSignature2(string timespan, string nonce, string token = Token)
        {
            string[] ArrTmp = { token, timespan, nonce };
            Array.Sort(ArrTmp);   //字典排序  
            string tmpStr = string.Join("", ArrTmp);
            //tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
            tmpStr = tmpStr.ToLower();
            return tmpStr;
        }
    }

}